package com.dy.lock.screen.component.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dy.lock.screen.component.CustomerLikeComponent;
import com.dy.lock.screen.constants.Constant;
import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.exception.ServerDisponseException;
import com.dy.lock.screen.jersey.api.EasemobMessages;
import com.dy.lock.screen.pojo.CustomerAttentionInfo;
import com.dy.lock.screen.pojo.CustomerBlacklistInfo;
import com.dy.lock.screen.pojo.CustomerLikeInfo;
import com.dy.lock.screen.pojo.CustomerMarkInfo;
import com.dy.lock.screen.pojo.MaterialCommentInfo;
import com.dy.lock.screen.pojo.UserInfo;
import com.dy.lock.screen.scoket.Head;
import com.dy.lock.screen.service.CustomerAttentionService;
import com.dy.lock.screen.service.CustomerBlacklistService;
import com.dy.lock.screen.service.CustomerLikeService;
import com.dy.lock.screen.service.CustomerMarkRelationService;
import com.dy.lock.screen.service.MaterialCommentService;
import com.dy.lock.screen.service.UserService;
import com.dy.lock.screen.utils.CommonUtil;
import com.dy.lock.screen.vo.CustomerLikeVo;
import com.dy.lock.screen.vo.EasemobVo;
import com.google.gson.Gson;

@Component("customerLikeComponent")
public class CustomerLikeComponentImpl implements CustomerLikeComponent {

	private static final Logger log = Logger
			.getLogger(CustomerLikeComponentImpl.class);
	private Gson gson;

	@Resource(name = "customerLikeService")
	private CustomerLikeService customerLikeService;
	@Resource(name = "userService")
	private UserService userService;
	@Resource(name = "customerAttentionService")
	private CustomerAttentionService customerAttentionService;
	@Resource(name = "materialCommentService")
	private MaterialCommentService materialCommentService;
	@Resource(name = "customerBlacklistService")
	private CustomerBlacklistService customerBlacklistService;
	@Resource(name = "customerMarkRelationService")
	private CustomerMarkRelationService customerMarkRelationService;

	public CustomerLikeComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public boolean materialLikeOrCancelLike(String body, Head head) {
		CustomerLikeVo vo = gson.fromJson(body, CustomerLikeVo.class);
		if (vo != null) {
			CustomerLikeInfo likeInfo = new CustomerLikeInfo();
			likeInfo.setUserId(vo.getUserId());
			likeInfo.setMaterialId(vo.getMaterialId());
			likeInfo.setLikeType(Constant.MATERIAL_LIKE);
			String result = "";
			int resu = -1;
			if (vo.isLikeOrNot()) {
				CustomerLikeInfo cli = this.customerLikeService
						.queryByMidAndCid(likeInfo);
				if (cli == null) {
					result = this.customerLikeService.save(likeInfo);
				} else {
					log.info("requestId:" + head.getRequestId()
							+ "用户已经对此文章点过赞。");
					throw new ServerDisponseException(
							TransmissionCode.MATERIAL_LIKED.getCode(),
							TransmissionCode.MATERIAL_LIKED.getMessage());
				}
			} else {
				resu = this.customerLikeService.delete(likeInfo);
				if (resu <= 0) {
					log.info("requestId:" + head.getRequestId()
							+ "用户对此文章还没有点过赞，不能取消点赞。");
					throw new ServerDisponseException(
							TransmissionCode.NOT_LIKE_CAN_NOT_CANCEL.getCode(),
							TransmissionCode.NOT_LIKE_CAN_NOT_CANCEL
									.getMessage());
				}
			}

			if (StringUtils.isNoneBlank(result) || resu > 0) {
				return true;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",用户点赞素材操作时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}

	}

	@Override
	public boolean materialCommentLikeOrCancelLike(String body, Head head) {
		CustomerLikeVo vo = gson.fromJson(body, CustomerLikeVo.class);
		if (vo != null) {
			MaterialCommentInfo mater = this.materialCommentService
					.queryByPrimaryKey(vo.getCommentId());
			CustomerBlacklistInfo blacklistInfo = new CustomerBlacklistInfo();
			blacklistInfo.setBlackCustomer(mater.getUserId());
			blacklistInfo.setBeBlackedCustomer(vo.getUserId());
			CustomerBlacklistInfo bl = customerBlacklistService
					.queryByBlackIdAndBeBlackId(blacklistInfo);
			if (bl != null) {
				log.info("requestId:" + head.getRequestId()
						+ "当前用户已把该用户加入黑名单，不能再对此用户的文章评论点赞。");
				throw new ServerDisponseException(
						TransmissionCode.DO_NOT_LIKE_USER_BECAUSE_BLACK_USER
								.getCode(),
						TransmissionCode.DO_NOT_LIKE_USER_BECAUSE_BLACK_USER
								.getMessage());
			}
			CustomerLikeInfo likeInfo = new CustomerLikeInfo();
			likeInfo.setUserId(vo.getUserId());
			likeInfo.setCommentId(vo.getCommentId());
			likeInfo.setMaterialId(vo.getMaterialId());
			likeInfo.setLikeType(Constant.MATERIAL_COMMENT_LIKE);
			String result = "";
			int resu = -1;
			if (vo.isLikeOrNot()) {
				CustomerLikeInfo cli = this.customerLikeService
						.queryByMidAndCid(likeInfo);
				if (cli == null) {
					result = this.customerLikeService.save(likeInfo);
				} else {
					log.info("requestId:" + head.getRequestId()
							+ "用户已经对此文章评论点过赞。");
					throw new ServerDisponseException(
							TransmissionCode.MATERIAL_LIKED.getCode(),
							TransmissionCode.MATERIAL_LIKED.getMessage());
				}
			} else {
				resu = this.customerLikeService.delete(likeInfo);
				if (resu <= 0) {
					log.info("requestId:" + head.getRequestId()
							+ "用户对此文章评论还没有点过赞，不能取消点赞。");
					throw new ServerDisponseException(
							TransmissionCode.NOT_LIKE_CAN_NOT_CANCEL.getCode(),
							TransmissionCode.NOT_LIKE_CAN_NOT_CANCEL
									.getMessage());
				}
			}

			if (StringUtils.isNoneBlank(result) || resu > 0) {
				if (vo.isLikeOrNot()) {
					// CustomerAttentionInfo attInfo = new
					// CustomerAttentionInfo();
					// attInfo.setBeConcernedId(vo.getUserId());
					// List<String> sendUserIds = this.customerAttentionService
					// .queryByAidOrBeid(attInfo);
					// 消息要发送的人
					List<String> sendUserIds = new ArrayList<String>();
					if (mater != null
							&& !vo.getUserId().equals(mater.getUserId())) {
						String materialUserId = mater.getUserId();
						sendUserIds.add(materialUserId);

						UserInfo userInfo = this.userService.queryByUserId(vo
								.getUserId(), head);
						String username = userInfo.getUserName();
						if (StringUtils.isBlank(username)) {
							username = vo.getUserId();
						}
						EasemobVo easemobVo = new EasemobVo();
						// 谁发的消息
						easemobVo.setUserId(vo.getUserId());
						easemobVo.setUserName(username);
						easemobVo.setCommonCommentOrLikeId(result);
						easemobVo
								.setMessageType(Constant.MESSAGE_TYPE_COMMON_LIKE);
						easemobVo.setMessageTime(new Date());
						List<String> failedUserId = EasemobMessages
								.sendMessages(vo.getUserId(), sendUserIds, gson
										.toJson(easemobVo));
						if (failedUserId != null && !failedUserId.isEmpty()) {
							log.info("requestId:" + head.getRequestId()
									+ ",文章评论点赞时，发送消息的失败用户ID："
									+ failedUserId.toString());
						}
					}
				}
				return true;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId()
					+ ",用户文章评论点赞操作时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}

	}

	@Override
	public List<CustomerLikeInfo> list(String body, Head head) {
		CustomerLikeVo vo = gson.fromJson(body, CustomerLikeVo.class);
		if (vo != null) {
			Integer currentPage = vo.getPageIndex();
			Integer pageSize = vo.getPageCount();
			Integer pageStart = 1;
			Integer pageEnd = 10;
			if (currentPage != null && pageSize != null) {
				pageStart = (currentPage - 1) * pageSize + 1;
				pageEnd = currentPage * pageSize;
			}
			Map<String, Object> para = new HashMap<String, Object>();
			para.put("pageStart", pageStart);
			para.put("pageEnd", pageEnd);
			// if (StringUtils.isNotBlank(vo.getUserId())) {
			// para.put("userId", vo.getUserId());
			// }
			if (StringUtils.isNotBlank(vo.getCommentId())) {
				para.put("commentId", vo.getCommentId());
			}
			para.put("likeType", vo.getLikeType());

			List<CustomerLikeInfo> list = this.customerLikeService
					.queryPage(para);
			if (list != null && !list.isEmpty()) {
				for (CustomerLikeInfo like : list) {
					like.setCommentPicPath(this.splitToString(like
							.getCommentPicPath(), ";"));
					like.setMaterialPic(CommonUtil
							.getUrlPrefixApi("photo.url.prefix.path")
							+ like.getMaterialPic());
					if (StringUtils.isNoneBlank(like.getHeaderPath())) {
						like.setHeaderPath(CommonUtil
								.getUrlPrefixApi("photo.url.prefix.path.api")
								+ like.getHeaderPath());
					}
					CustomerAttentionInfo att = new CustomerAttentionInfo();
					att.setAttentionId(vo.getUserId());
					att.setBeConcernedId(like.getUserId());
					CustomerAttentionInfo atten = this.customerAttentionService
							.queryByAidAndBeid(att);
					if (atten != null) {
						like.setAttentioned(true);
					}
					List<CustomerMarkInfo> markInfos = this.customerMarkRelationService
							.queryListByCid(like.getUserId());
					like.setMarkInfoList(markInfos);
				}
				return list;
			} else {
				return new ArrayList<CustomerLikeInfo>();
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",获取点赞列表操作时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public List<CustomerLikeInfo> myLikeList(String body, Head head) {
		CustomerLikeVo vo = gson.fromJson(body, CustomerLikeVo.class);
		if (vo != null) {
			Integer currentPage = vo.getPageIndex();
			Integer pageSize = vo.getPageCount();
			Integer pageStart = 1;
			Integer pageEnd = 10;
			if (currentPage != null && pageSize != null) {
				pageStart = (currentPage - 1) * pageSize + 1;
				pageEnd = currentPage * pageSize;
			}
			Map<String, Object> para = new HashMap<String, Object>();
			para.put("pageStart", pageStart);
			para.put("pageEnd", pageEnd);
			para.put("userId", vo.getUserId());

			List<CustomerLikeInfo> list = this.customerLikeService
					.queryPage(para);
			if (list != null && !list.isEmpty()) {
				for (CustomerLikeInfo like : list) {
					// 取第一张
					like.setCommentPicPath(this.splitToString(like
							.getCommentPicPath(), ";"));
					like.setMaterialPic(CommonUtil
							.getUrlPrefixApi("photo.url.prefix.path")
							+ like.getMaterialPic());
					if (StringUtils.isNoneBlank(like.getHeaderPath())) {
						like.setHeaderPath(CommonUtil
								.getUrlPrefixApi("photo.url.prefix.path.api")
								+ like.getHeaderPath());
					}
					List<CustomerMarkInfo> markInfos = this.customerMarkRelationService
							.queryListByCid(like.getUserId());
					like.setMarkInfoList(markInfos);
				}
				return list;
			} else {
				return new ArrayList<CustomerLikeInfo>();
			}
		} else {
			log
					.info("requestId:" + head.getRequestId()
							+ ",获取我的赞列表操作时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	/**
	 * 把指定字符串已指定方式分割，然后在转换成特定字符串
	 * 
	 * @param targetStr
	 * @param regex
	 * @return
	 */
	private String splitToString(String targetStr, String regex) {
		StringBuilder sb = new StringBuilder();
		String prefix = CommonUtil.getUrlPrefixApi("photo.url.prefix.path.api");
		if (StringUtils.isNotBlank(targetStr)) {
			String[] array = targetStr.split(regex);
			if (array != null && array.length > 0) {
				sb.append(prefix + array[0]);
			}
			String result = sb.toString();
			return result;
		} else {
			return "";
		}
	}

}
